<template>
  <div>
    <el-form :model="form" ref="ruleFormRef" :rules="rules" :inline="true">
      <div class="formitem" style="flex-wrap: wrap">
        <div class="label" style="margin-top: 6px">
          <span>*</span>
          认证方式
        </div>
        <div class="type">
          <div class="btn" :class="{ active: authType === 1 }" @click="authType = 1">法定代表人身份证简项</div>
        </div>
        <div class="auth_tip">
          <p>法定代表人认证：</p>
          <p>1、需填写法定代表人基本信息，以及通过法定代表人本人办理的手机号验证，即可完成认证</p>
          <p>2、仅支持大陆身份证号</p>
        </div>
      </div>
      <div class="formitem">
        <div class="label" style="margin-top: 6px">
          <span>*</span>
          企业名称
        </div>
        <el-form-item prop="name" style="width: 100%">
          <el-input v-model="form.name" style="width: 100%" disabled />
        </el-form-item>
      </div>
      <div class="formitem">
        <div class="label" style="margin-top: -4px">
          <span>*</span>
          统一社会信用代码或工商注册号
        </div>
        <el-form-item prop="social_credit_code" style="width: 100%">
          <el-input v-model="form.social_credit_code" style="width: 100%" disabled />
        </el-form-item>
      </div>
      <div class="formitem">
        <div class="label" style="margin-top: 6px">
          <span>*</span>
          法定代表人姓名
        </div>
        <el-form-item prop="legal_person" style="width: 100%">
          <el-input v-model="form.legal_person" style="width: 100%" disabled />
        </el-form-item>
      </div>
      <div class="formitem">
        <div class="label" style="margin-top: 6px">
          <span>*</span>
          法定代表人身份证号
        </div>
        <el-form-item prop="legal_person_id" style="width: 100%">
          <el-input v-model="form.legal_person_id" style="width: 100%"  disabled />
        </el-form-item>
      </div>
      <div class="formitem">
        <div class="label" style="margin-top: 6px">
          <span>*</span>
          法定代表人手机号
        </div>
        <el-form-item prop="mobile" style="width: 100%">
          <el-input v-model="form.mobile" style="width: 60%; margin-right: 10px" />
          <el-button :disabled="countDisabled" @click="getCode">{{ countText }}</el-button>
        </el-form-item>
      </div>

      <div class="formitem">
        <div class="label" style="margin-top: 6px">
          <span>*</span>
          验证码
        </div>
        <el-form-item prop="code" style="width: 100%">
          <el-input v-model="form.code" style="width: 100%" />
        </el-form-item>
      </div>
      <!-- <div class="formitem">
                <div class="label" style="margin-top: 6px;"><span>*</span>验证码</div>
                <el-form-item prop="code" style="width: 100%">
                    <el-input v-model="form.code" style="flex: 1; margin-right: 5px;" />
                    <CountDownBtn :phone="form.mobile" />
                </el-form-item>
            </div> -->

  
      <el-form-item style="width: 100%">
        <el-button class="submit" @click="submitForm(ruleFormRef)">开始认证</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted } from "vue";
  import type { FormInstance, FormRules } from "element-plus";
  import CountDownBtn from "@/components/CountDownBtn.vue";
  import { useCompanyDataStore } from "@/store/companys";
  import { authCompanyMobile3, authCaptchaVerify } from "@/api/cf";

  const companyDataStore = useCompanyDataStore();
  const props = defineProps<{
    formData: {
      name: string;
      social_credit_code: string;
      legal_person: string;
      id: number;
    };
  }>();
  const countDisabled = ref(false);
  const countText = ref("获取验证码");
  const authType = ref(1);
  const authTypeList = ref(["法定代表人身份证简项", "企业法人扫脸认证"]);
  const form = reactive({
    name: "",
    social_credit_code: "",
    legal_person: "",
    id: 0,
    legal_person_id: "",
    mobile: "",
    code: "",
  });

  onMounted(() => {
    // companyDataStore.currentComanyInfo.value
    form.name = companyDataStore.currentComanyInfo.name;
    form.social_credit_code = companyDataStore.currentComanyInfo.social_credit_code;
    form.legal_person_id = companyDataStore.currentComanyInfo.legal_person_id;

    form.legal_person = companyDataStore.currentComanyInfo.legal_person;
    form.id = companyDataStore.currentComanyInfo.id;
  });

  const validateIDCard = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error("请输入法定代表人身份证号"));
      return;
    }

    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;

    if (!idCardRegex.test(value)) {
      callback(new Error("身份证号格式不正确"));
      return;
    }

    const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    let sum = 0;

    for (let i = 0; i < 17; i++) {
      sum += parseInt(value[i]) * weights[i];
    }

    const lastChar = value[17].toUpperCase();
    if (lastChar !== checkCodes[sum % 11]) {
      callback(new Error("身份证号校验失败，请检查"));
    } else {
      callback();
    }
  };

  const validateMobile = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error("请输入法定代表人手机号"));
      return;
    }

    const mobileRegex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;

    if (!mobileRegex.test(value)) {
      callback(new Error("请输入正确的11位手机号"));
    } else {
      callback();
    }
  };
  const loading = ref(false)
  const rules = reactive<FormRules>({
    legal_person_id: [{ required: true, validator: validateIDCard, trigger: ["blur", "change"] }],
    mobile: [{ required: true, validator: validateMobile, trigger: ["blur", "change"] }],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  });
  const ruleFormRef = ref<FormInstance>();

  const emit = defineEmits(["submit-success"]);

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        loading.value = true;
        authCaptchaVerify({
          code: form.code,
          type: 2,
          id: form.id,
        })
          .then(res => {
             emit('submit-success', {
                ...form
            })
            loading.value = false;
          })
          .catch(err => {
            loading.value = false;
            console.log(err);
          });
      } else {
        console.log("error submit!", fields);
      }
    });
  };

  const getCode = () => {
    if (form.mobile === null) {
      ElMessage.error("请输入手机号");
      return;
    } else {
      if (!/^1[3456789]\d{9}$/.test(form.mobile)) {
        ElMessage.error("手机号格式不正确");
        return;
      }
    }

    countDisabled.value = true;
    authCompanyMobile3({
      id: form.id,
      mobile: form.mobile,
    })
      .then(() => {
        ElMessage.success("发送成功");
        let currentTime = 60;
        countText.value = "60S重新获取";
        let interval = setInterval(() => {
          currentTime--;
          countText.value = currentTime + "S" + "重新获取";
          if (currentTime <= 0) {
            clearInterval(interval);
            countText.value = "重新获取";
            countDisabled.value = false;
          }
        }, 1000);
      })
      .catch(err => {
        countDisabled.value = true;
      });
  };
</script>
<style lang="scss" scoped>
.formitem {
  width: 100%;
  display: flex;
  margin-bottom: 15px;

  .label {
    width: 145px;
    text-align: right;
    margin-right: 16px;
    line-height: 20px;
    font-size: 14px;
    color: #666;
    flex-shrink: 0;

    span {
      color: #f00;
    }
  }

  .type {
    display: flex;

    .btn {
      height: 30px;
      line-height: 30px;
      padding: 0 10px;
      border-radius: 5px;
      font-size: 14px;
      background-color: #f7f7f7;
      color: #666;
      border: solid 1px #eaeaea;
      margin-right: 10px;
      cursor: pointer;

      &.active {
        background-color: #fff;
        color: #01509f;
        border-color: #01509f;
      }
    }
  }

  .auth_tip {
    width: 353px;
    font-size: 14px;
    color: #999;
    border-radius: 5px;
    background-color: #f3f8fb;
    padding: 10px 15px;
    margin-left: 152px;
    margin-top: 15px;
  }
}

.submit {
  width: 200px;
  height: 37px;
  color: #fff;
  background-color: #01509f;
  margin: 25px auto 0;
}
</style>
